import { _collectList, _addOrDelCollect } from "../../../service/api";

Page({
  data: {
    page: 1,
    size: 20,
    typeId: 0,
    collectList: [],
    count: 0,
  },
  onLoad: function (options) {
    this.initData();
  },
  async initData() {
    const { page, size } = this.data;
    const res = await _collectList({ page, size });
    this.setData({
      collectList: [...this.data.collectList, ...res.collectList],
      count: res.count,
    });
  },
  // 加载更多
  handleReachBottom() {
    const { page, size, count } = this.data;
    if (page < Math.ceil(count / size)) {
      this.setData({ page: page + 1 });
      this.initData();
    }
  },
  // 点击跳转、长按删除
  async handleGoodsItemTap(e) {
    const index = e.target.dataset.index;
    let { collectList, touch_end, touch_start, typeId } = this.data;
    let touchTime = touch_end - touch_start;
    if (touchTime > 350) {
      const result = await wx.showModal({ content: "确定删除吗" });
      if (result.confirm) {
        const res = await _addOrDelCollect({ typeId: typeId, valueId: collectList[index].value_id });
        if (res.errno === 200) {
          wx.showToast({ title: "删除成功", icon: "success" });
          collectList.splice(index, 1);
          this.setData({ collectList: collectList });
        }
      }
    } else {
      wx.navigateTo({
        url: "/pages/goods/goods_detail?id=" + collectList[index].value_id,
      });
    }
  },
  // 按下开始
  handleTouchStart(e) {
    this.setData({ touch_start: e.timeStamp });
  },
  // 按下结束
  handleTouchEnd(e) {
    this.setData({ touch_end: e.timeStamp });
  },
});
